package com.xhai.mybatis.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xhai.common.constant.SecurityConstants;
import com.xhai.common.utils.SecurityUtils;
import com.xhai.common.utils.classes.StringUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Override
    public void insertFill(MetaObject metaObject) {
        String username = SecurityUtils.getUsername();
        if (StringUtils.isEmpty(username)) {
            username = SecurityConstants.ADMIN_USERNAME;//表示是管理员创建的
        }

        this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "createUsername", String.class, username);
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateUsername", String.class, username);
        this.strictInsertFill(metaObject, "logicDelFlag", Character.class, '0');
        this.strictInsertFill(metaObject, "version", Integer.class, 1);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String username = SecurityUtils.getUsername();
        if (StringUtils.isEmpty(username)) {
            username = SecurityConstants.ADMIN_USERNAME;//表示是管理员创建的
        }
        this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
        this.strictInsertFill(metaObject, "updateUsername", String.class, username);
    }
}